package com.zenithmind.document.pojo.vo;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 文档标签VO
 * 遵循单一职责原则：专注于标签数据展示
 * 遵循开闭原则：支持字段的扩展
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Data
@Schema(description = "文档标签VO")
public class DocumentTagVO {

    @Schema(description = "标签ID", example = "tag123456")
    private String id;

    @Schema(description = "标签名称", example = "Java")
    private String name;

    @Schema(description = "标签显示名称", example = "Java编程语言")
    private String displayName;

    @Schema(description = "标签描述", example = "Java编程语言相关文档")
    private String description;

    @Schema(description = "标签颜色", example = "#FF5722")
    private String color;

    @Schema(description = "标签图标", example = "fa-java")
    private String icon;

    @Schema(description = "标签分类", example = "编程语言")
    private String category;

    @Schema(description = "分类路径", example = "技术/编程语言")
    private String categoryPath;

    @Schema(description = "父标签ID", example = "tag123456")
    private String parentTagId;

    @Schema(description = "父标签名称", example = "编程语言")
    private String parentTagName;

    @Schema(description = "标签级别", example = "1")
    private Integer level;

    @Schema(description = "标签路径", example = "编程语言/Java")
    private String tagPath;

    @Schema(description = "排序权重", example = "100")
    private Integer sortWeight;

    @Schema(description = "是否系统标签", example = "false")
    private Boolean isSystemTag;

    @Schema(description = "是否公开标签", example = "true")
    private Boolean isPublic;

    @Schema(description = "是否推荐标签", example = "true")
    private Boolean isRecommended;

    @Schema(description = "是否热门标签", example = "true")
    private Boolean isHot;

    @Schema(description = "标签别名", example = "java,JAVA,Java语言")
    private String aliases;

    @Schema(description = "别名数组", example = "[\"java\", \"JAVA\", \"Java语言\"]")
    private String[] aliasArray;

    @Schema(description = "相关关键词", example = "编程,开发,后端")
    private String keywords;

    @Schema(description = "关键词数组", example = "[\"编程\", \"开发\", \"后端\"]")
    private String[] keywordArray;

    @Schema(description = "标签权重", example = "1.2")
    private Double weight;

    @Schema(description = "使用次数", example = "156")
    private Integer usageCount;

    @Schema(description = "文档数量", example = "89")
    private Integer documentCount;

    @Schema(description = "子标签数量", example = "5")
    private Integer childrenCount;

    @Schema(description = "使用限制", example = "{\"maxUsage\": 1000}")
    private String usageRestrictions;

    @Schema(description = "使用限制描述", example = "最大使用次数: 1000")
    private String usageRestrictionsDesc;

    @Schema(description = "标签规则", example = "{\"autoApply\": true}")
    private String tagRules;

    @Schema(description = "标签规则描述", example = "自动应用规则已启用")
    private String tagRulesDesc;

    @Schema(description = "创建人ID", example = "user123456")
    private String creatorId;

    @Schema(description = "创建人姓名", example = "张三")
    private String creatorName;

    @Schema(description = "创建人头像", example = "https://example.com/avatar.jpg")
    private String creatorAvatar;

    @Schema(description = "创建来源", example = "MANUAL")
    private String createSource;

    @Schema(description = "创建来源描述", example = "手动创建")
    private String createSourceDesc;

    @Schema(description = "语言代码", example = "zh-CN")
    private String languageCode;

    @Schema(description = "语言名称", example = "简体中文")
    private String languageName;

    @Schema(description = "地域代码", example = "CN")
    private String regionCode;

    @Schema(description = "地域名称", example = "中国")
    private String regionName;

    @Schema(description = "标签状态", example = "ACTIVE")
    private String status;

    @Schema(description = "状态描述", example = "活跃")
    private String statusDesc;

    @Schema(description = "扩展属性", example = "{\"difficulty\": \"beginner\"}")
    private String extendedProperties;

    @Schema(description = "备注", example = "系统自动创建的编程语言标签")
    private String remarks;

    @Schema(description = "版本号", example = "2")
    private Integer version;

    @Schema(description = "是否启用", example = "true")
    private Boolean isEnabled;

    @Schema(description = "审核状态", example = "APPROVED")
    private String reviewStatus;

    @Schema(description = "审核状态描述", example = "已审核")
    private String reviewStatusDesc;

    @Schema(description = "审核意见", example = "标签创建合理")
    private String reviewComment;

    @Schema(description = "审核人", example = "审核员")
    private String reviewerName;

    @Schema(description = "审核时间", example = "2025-01-09T11:00:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime reviewTime;

    @Schema(description = "热度分数", example = "85")
    private Integer hotScore;

    @Schema(description = "质量分数", example = "90")
    private Integer qualityScore;

    @Schema(description = "流行度", example = "HIGH", allowableValues = {"LOW", "MEDIUM", "HIGH", "VERY_HIGH"})
    private String popularity;

    @Schema(description = "趋势", example = "RISING", allowableValues = {"RISING", "STABLE", "DECLINING"})
    private String trend;

    @Schema(description = "最后使用时间", example = "2025-01-09T15:30:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime lastUsedTime;

    @Schema(description = "最后使用时间描述", example = "2小时前")
    private String lastUsedTimeDesc;

    @Schema(description = "创建时间", example = "2025-01-09T10:00:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime createTime;

    @Schema(description = "创建时间描述", example = "3天前")
    private String createTimeDesc;

    @Schema(description = "更新时间", example = "2025-01-09T10:30:00")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updateTime;

    @Schema(description = "更新时间描述", example = "1小时前")
    private String updateTimeDesc;

    /**
     * 获取创建来源描述
     */
    public String getCreateSourceDescription() {
        if (createSource == null) return "";
        
        switch (createSource.toUpperCase()) {
            case "MANUAL": return "手动创建";
            case "AUTO": return "自动创建";
            case "IMPORT": return "导入创建";
            case "SYSTEM": return "系统创建";
            default: return createSource;
        }
    }

    /**
     * 获取状态描述
     */
    public String getStatusDescription() {
        if (status == null) return "";
        
        switch (status.toUpperCase()) {
            case "ACTIVE": return "活跃";
            case "INACTIVE": return "非活跃";
            case "PENDING": return "待审核";
            case "DEPRECATED": return "已废弃";
            default: return status;
        }
    }

    /**
     * 获取审核状态描述
     */
    public String getReviewStatusDescription() {
        if (reviewStatus == null) return "";
        
        switch (reviewStatus.toUpperCase()) {
            case "PENDING": return "待审核";
            case "APPROVED": return "已审核";
            case "REJECTED": return "已拒绝";
            default: return reviewStatus;
        }
    }

    /**
     * 获取流行度描述
     */
    public String getPopularityDescription() {
        if (popularity == null) return "";
        
        switch (popularity.toUpperCase()) {
            case "LOW": return "低";
            case "MEDIUM": return "中等";
            case "HIGH": return "高";
            case "VERY_HIGH": return "非常高";
            default: return popularity;
        }
    }

    /**
     * 获取趋势描述
     */
    public String getTrendDescription() {
        if (trend == null) return "";
        
        switch (trend.toUpperCase()) {
            case "RISING": return "上升";
            case "STABLE": return "稳定";
            case "DECLINING": return "下降";
            default: return trend;
        }
    }

    /**
     * 获取时间描述
     */
    public String getTimeDescription(LocalDateTime time) {
        if (time == null) return "";
        
        LocalDateTime now = LocalDateTime.now();
        long minutes = ChronoUnit.MINUTES.between(time, now);
        
        if (minutes < 1) return "刚刚";
        else if (minutes < 60) return minutes + "分钟前";
        else if (minutes < 1440) return (minutes / 60) + "小时前";
        else if (minutes < 43200) return (minutes / 1440) + "天前";
        else return time.toLocalDate().toString();
    }

    /**
     * 获取别名数组
     */
    public String[] getAliasArray() {
        if (aliases == null || aliases.trim().isEmpty()) {
            return new String[0];
        }
        return aliases.split(",");
    }

    /**
     * 获取关键词数组
     */
    public String[] getKeywordArray() {
        if (keywords == null || keywords.trim().isEmpty()) {
            return new String[0];
        }
        return keywords.split(",");
    }

    /**
     * 获取标签全路径
     */
    public String getFullPath() {
        if (tagPath != null && !tagPath.trim().isEmpty()) {
            return tagPath;
        }
        
        if (parentTagName != null && !parentTagName.trim().isEmpty()) {
            return parentTagName + "/" + name;
        }
        
        return name;
    }

    /**
     * 获取显示名称
     */
    public String getDisplayName() {
        if (displayName != null && !displayName.trim().isEmpty()) {
            return displayName;
        }
        return name;
    }

    /**
     * 是否为系统标签
     */
    public boolean isSystemTag() {
        return isSystemTag != null && isSystemTag;
    }

    /**
     * 是否为公开标签
     */
    public boolean isPublicTag() {
        return isPublic == null || isPublic;
    }

    /**
     * 是否为推荐标签
     */
    public boolean isRecommendedTag() {
        return isRecommended != null && isRecommended;
    }

    /**
     * 是否为热门标签
     */
    public boolean isHotTag() {
        return isHot != null && isHot;
    }

    /**
     * 是否为根标签
     */
    public boolean isRootTag() {
        return parentTagId == null || parentTagId.trim().isEmpty();
    }

    /**
     * 是否为叶子标签
     */
    public boolean isLeafTag() {
        return childrenCount == null || childrenCount == 0;
    }

    /**
     * 是否有子标签
     */
    public boolean hasChildren() {
        return childrenCount != null && childrenCount > 0;
    }

    /**
     * 是否有别名
     */
    public boolean hasAliases() {
        return aliases != null && !aliases.trim().isEmpty();
    }

    /**
     * 是否有关键词
     */
    public boolean hasKeywords() {
        return keywords != null && !keywords.trim().isEmpty();
    }

    /**
     * 是否有使用限制
     */
    public boolean hasUsageRestrictions() {
        return usageRestrictions != null && !usageRestrictions.trim().isEmpty();
    }

    /**
     * 是否有标签规则
     */
    public boolean hasTagRules() {
        return tagRules != null && !tagRules.trim().isEmpty();
    }

    /**
     * 是否为活跃标签
     */
    public boolean isActiveTag() {
        return "ACTIVE".equalsIgnoreCase(status) && (isEnabled == null || isEnabled);
    }

    /**
     * 是否需要审核
     */
    public boolean needsReview() {
        return "PENDING".equalsIgnoreCase(reviewStatus);
    }

    /**
     * 是否已审核通过
     */
    public boolean isApproved() {
        return "APPROVED".equalsIgnoreCase(reviewStatus);
    }

    /**
     * 是否为高质量标签
     */
    public boolean isHighQuality() {
        return qualityScore != null && qualityScore >= 80;
    }

    /**
     * 是否为热门标签（基于使用次数）
     */
    public boolean isPopularByUsage() {
        return usageCount != null && usageCount >= 100;
    }

    /**
     * 是否为新标签（7天内创建）
     */
    public boolean isNewTag() {
        if (createTime == null) return false;
        return ChronoUnit.DAYS.between(createTime, LocalDateTime.now()) <= 7;
    }

    /**
     * 是否为最近使用的标签（24小时内）
     */
    public boolean isRecentlyUsed() {
        if (lastUsedTime == null) return false;
        return ChronoUnit.HOURS.between(lastUsedTime, LocalDateTime.now()) <= 24;
    }

    /**
     * 计算标签活跃度分数
     */
    public double calculateActivityScore() {
        double score = 0.0;
        
        // 使用次数权重 40%
        if (usageCount != null) {
            score += Math.min(usageCount / 1000.0, 1.0) * 0.4;
        }
        
        // 文档数量权重 30%
        if (documentCount != null) {
            score += Math.min(documentCount / 500.0, 1.0) * 0.3;
        }
        
        // 最近使用权重 20%
        if (lastUsedTime != null) {
            long daysSinceLastUsed = ChronoUnit.DAYS.between(lastUsedTime, LocalDateTime.now());
            score += Math.max(0, (30 - daysSinceLastUsed) / 30.0) * 0.2;
        }
        
        // 热度分数权重 10%
        if (hotScore != null) {
            score += (hotScore / 100.0) * 0.1;
        }
        
        return Math.min(score, 1.0);
    }

    /**
     * 计算标签重要性分数
     */
    public double calculateImportanceScore() {
        double score = 0.0;
        
        // 系统标签加分
        if (isSystemTag()) score += 0.3;
        
        // 推荐标签加分
        if (isRecommendedTag()) score += 0.2;
        
        // 热门标签加分
        if (isHotTag()) score += 0.2;
        
        // 权重加分
        if (weight != null) {
            score += Math.min(weight / 5.0, 0.2);
        }
        
        // 质量分数加分
        if (qualityScore != null) {
            score += (qualityScore / 100.0) * 0.1;
        }
        
        return Math.min(score, 1.0);
    }

    /**
     * 获取标签综合评分
     */
    public double getOverallRating() {
        double activityScore = calculateActivityScore();
        double importanceScore = calculateImportanceScore();
        
        // 活跃度权重 60%，重要性权重 40%
        return activityScore * 0.6 + importanceScore * 0.4;
    }

    /**
     * 获取标签等级
     */
    public String getTagGrade() {
        double rating = getOverallRating();
        
        if (rating >= 0.9) return "S";
        else if (rating >= 0.8) return "A";
        else if (rating >= 0.7) return "B";
        else if (rating >= 0.6) return "C";
        else return "D";
    }
}
